﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using DAL;
using HomeStayWebCP.Models;
using HomeStayWebCP.Models.BusinessObject;
using System.Web.Security;
using HomeStayWebCP.Utility;

namespace HomeStayWebCP.Controllers.Admin
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
      
        public String CheckLogin(string usernameinput, string password)
        {
            CryptorEngine crytor = new CryptorEngine();
            UserModel model = new UserModel();
            string username = usernameinput.Trim().ToLower();
            string passwordlogin = password.ToLower();
            User user = model.SelectUserbyUserName(username);
            
            if (user != null)
            {
                string passwordcheck = crytor.Decrypt(user.Password, true);
                if (user.Username == username && passwordcheck == passwordlogin && user.RoleID >= 2)
                {
                    HttpContext.Session.Add("usernameAdmin", user.Username);
                    HttpContext.Session.Add("roleID", user.RoleID);
                    return "Admin";
                }
            }
            return "Fail";
        }
        public ActionResult AdminPage()
        {
            if (HttpContext.Session["roleID"] != null && !HttpContext.Session["roleID"].ToString().Equals(String.Empty))
            {
                int roleID = Int32.Parse(HttpContext.Session["roleID"].ToString());
                //>=2 means admin
                if (roleID > 1)
                {
                    return View();
                }
                else
                {
                    //redirect to You doesn't have permission
                    return RedirectToAction("Login", "Admin");
                }
            }
            else
            {
                //redirect to You doesn't have permission
                return RedirectToAction("Login", "Admin");
            }
            
        }
        
        public  ActionResult Login()
        {
            return View();
        }
        //Log off function
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session["usernameAdmin"] = null;
            Session["roleID"] = null;
            return RedirectToAction("Login", "Admin");
        }
        
    }
}
